package com.demo.controls;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.demo.common.model.Goods;
import com.demo.common.model.Ordergoods;
import com.demo.common.model.Place;
import com.demo.common.model.Shoppingcar;
import com.demo.common.model.Userorder;
import com.jfinal.kit.JsonKit;
import com.jfinal.log.Log;

/**
 * IndexController
 */
public class UserOrderController extends BaseController {
	public void index() {
		int userid;
		if ((userid = checkToken()) < 0) {
			return;
		}

		List<Userorder> resultList = Userorder.dao
				.find("select * from userorder where fuserid = ? and ordertype = ? and ispay = ? order by id desc",
						userid, getParaToInt("ordertype", ORDERTYPE_DEFAULT),
						getParaToInt("type", PAY_STAUS_NOT));
		JSONArray ja = JSONArray.parseArray(JsonKit.toJson(resultList));
		for (int i = 0; i < ja.size(); i++) {
			List<Ordergoods> OrdergoodsList = Ordergoods.dao
					.find("select * from ordergoods where forderid = ?  order by id desc",
							ja.getJSONObject(i).getIntValue("id"));
			JSONArray jaOrdergoodsList = JSONArray.parseArray(JsonKit
					.toJson(OrdergoodsList));
			JSONArray goodList = new JSONArray();
			for (int j = 0; j < jaOrdergoodsList.size(); j++) {
				goodList.add(getGoods(jaOrdergoodsList.getJSONObject(j)
						.getIntValue("fgoodsid")));
			}
			ja.getJSONObject(i).put("goods", goodList);
			Place place = Place.dao.findById(resultList.get(i).getPlaceid());
			ja.getJSONObject(i).put("place", place);
		}

		renderJson(ja.toString());
		return;
	}

	/**
	 * 每日订单列表
	 */
	public void daily() {
		int userid;
		if ((userid = checkToken()) < 0) {
			return;
		}

		List<Userorder> resultList = Userorder.dao
				.find("select * from userorder where fuserid = ? and ordertype = ? and ispay = ? order by id desc",
						userid, getParaToInt("ordertype", ORDERTYPE_DAILY),
						getParaToInt("type", PAY_STAUS_DONE));
		JSONArray ja = JSONArray.parseArray(JsonKit.toJson(resultList));
		for (int i = 0; i < ja.size(); i++) {
			List<Ordergoods> OrdergoodsList = Ordergoods.dao
					.find("select * from ordergoods where forderid = ?  order by id desc",
							ja.getJSONObject(i).getIntValue("id"));
			JSONArray jaOrdergoodsList = JSONArray.parseArray(JsonKit
					.toJson(OrdergoodsList));
			JSONArray goodList = new JSONArray();
			for (int j = 0; j < jaOrdergoodsList.size(); j++) {
				goodList.add(getGoods(jaOrdergoodsList.getJSONObject(j)
						.getIntValue("fgoodsid")));
			}
			ja.getJSONObject(i).put("goods", goodList);
			Place place = Place.dao.findById(resultList.get(i).getPlaceid());
			ja.getJSONObject(i).put("place", place);
		}

		renderJson(ja.toString());
		return;
	}

	public final int OderValueTime = 30 * 60 * 1000;

	/**
	 * 添加普通订单
	 */
	public void add() {

		int userid;
		if ((userid = checkToken()) < 0) {
			return;
		}
		int placeid = getParaToInt("placeid", 0);
		Place place = Place.dao.findById(placeid);
		if (place == null) {
			renderErr(ERR_ILLPAR, "place id " + placeid + " is not exist");
			return;
		} else if (place.getFuserid() != userid) {
			renderErr(ERR_ILLPAR, "place id " + placeid + " out of userid "
					+ userid);
			return;
		}

		Userorder order = new Userorder();
		order.setCreatetime(new Date(System.currentTimeMillis()));
		order.setEndtime(new Date(System.currentTimeMillis() + OderValueTime));
		order.setFuserid(userid);
		order.setIspay(0);// 0 is false
		order.setOrdertype(getParaToInt("ordertype", 0));
		order.setPaytype(getParaToInt("paytype", 0));

		// TODO 涉及多人订单. 显示金额 代付的关联订单

		order.setPostmanname("");
		order.setPostmanphone("");

		order.setPlaceid(placeid);
		order.setSendername("admin");

		List<Shoppingcar> goodsList = Shoppingcar.dao.find(
				"select * from shoppingcar where fuserid = ? ", userid);
		if (goodsList == null || goodsList.size() <= 0) {
			renderErr(ERR_ILLPAR, "Shoppingcar is null");
			return;
		}
		int totleprice = 0;
		for (int i = 0; i < goodsList.size(); i++) {
			Shoppingcar shoppingcar = goodsList.get(i);
			totleprice += Goods.dao.findById(shoppingcar.getFgoodsid())
					.getPrice();
		}
		order.setTotalprice(totleprice);
		boolean isOrderSuccess = order.save();
		if (!isOrderSuccess) {
			renderErr(ERR_DB, "order.save fail");
			return;
		} else {
			for (int i = 0; i < goodsList.size(); i++) {
				if (!goodsList.get(i).delete()) {

					Log.getLog(this.getClass()).warn(
							"Shoppingcar dele fail:" + goodsList.get(i));
					renderErr(ERR_DB, "Shoppingcar delete fail");
					return;
				}
			}
		}
		renderJson(order);

		for (int i = 0; i < goodsList.size(); i++) {
			Shoppingcar shoppingcar = goodsList.get(i);
			Ordergoods og = new Ordergoods();
			og.setFgoodsid(shoppingcar.getFgoodsid());
			og.setForderid(order.getId());
			og.save();
		}
		MsgController.add(MSGTYPE_ORDER, userid, "新的订单:" + order.getId(),
				USERID_SYSTEM, order.getId());
	}

	/**
	 * 添加每日订单
	 */
	public void addDaily() {
		int userid;
		if ((userid = checkToken()) < 0) {
			return;
		}
		int placeid = getParaToInt("placeid", 0);
		Place place = Place.dao.findById(placeid);
		if (place == null) {
			renderErr(ERR_ILLPAR, "place id " + placeid + " is not exist");
			return;
		} else if (place.getFuserid() != userid) {
			renderErr(ERR_ILLPAR, "place id " + placeid + " out of userid "
					+ userid);
			return;
		}
		String goodsidString = getPara("goodsid");
		if (goodsidString == null) {
			renderErr("goodsid==null");
			return;
		}

		int[] goodsid = getParToIntArray(goodsidString);
		if (goodsid == null) {
			renderErr("goodsid parse err");
			return;
		}

		String timeString = getPara("time");
		if (timeString == null) {
			renderErr("time==null");
			return;
		}

		long[] time = getParToLongArray(timeString);
		if (time == null) {
			renderErr("time parse err");
			return;
		}

		if (time.length != goodsid.length) {
			renderErr("time.length!=goodsid.length");
			return;
		}

		if (goodsid == null || goodsid.length <= 0) {
			renderErr(ERR_ILLPAR, "goodsid is null");
			return;
		}
		ArrayList<Userorder> userorders = new ArrayList<Userorder>();
		for (int j = 0; j < time.length; j++) {
			Userorder order = new Userorder();
			order.setCreatetime(new Date(System.currentTimeMillis()));
			order.setEndtime(new Date(System.currentTimeMillis()
					+ OderValueTime));
			order.setFuserid(userid);
			order.setIspay(PAY_STAUS_NOT);
			order.setOrdertype(ORDERTYPE_DAILY);
			order.setPaytype(getParaToInt("paytype", 0));
			order.setDispatchtime(new Date(time[j]));
			// TODO 涉及多人订单. 显示金额 代付的关联订单

			order.setPostmanname("");
			order.setPostmanphone("");
			order.setPlaceid(placeid);
			order.setSendername("admin");
			Goods goods = Goods.dao.findById(goodsid[j]);
			if (goods == null) {
				renderErr(ERR_ILLPAR, "goods not be found "+goodsid[j]);
				return;
			}
			int totleprice = goods.getPrice();
			order.setTotalprice(totleprice);
			boolean isOrderSuccess = order.save();
			if (!isOrderSuccess) {
				renderErr(ERR_DB, "order.save fail");
				return;
			}
			userorders.add(order);
			Ordergoods og = new Ordergoods();
			og.setFgoodsid(goodsid[j]);
			og.setForderid(order.getId());
			og.save();

			MsgController.add(MSGTYPE_ORDER, userid,
					"新的每日订单:" + order.getEndtime(), USERID_SYSTEM,
					order.getId());
		}
		renderJson(userorders);

	}

	public void remove() {

		int userid;
		if ((userid = checkToken()) < 0) {
			return;
		}

		int temp = getParaToInt("orderid", -1);
		if (temp < 0) {
			renderErr("orderid parse err");
			return;
		}

		List<Userorder> resultList = Userorder.dao.find(
				"select * from userorder where fuserid = ? and id = ?", userid,
				temp);
		for (int i = 0; i < resultList.size(); i++) {
			if (resultList.get(i).getId().intValue() == temp) {
				boolean result = Userorder.dao.deleteById(temp);
				if (result) {
					renderOK();
					return;
				}
			}
		}
		renderErr("delete order fail");
		return;
	}
}